package com.ceair.authorization.handler;

import com.ceair.entity.model.Result;
import com.ceair.util.JsonUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.http.MediaType;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.security.web.util.UrlUtils;

import java.nio.charset.StandardCharsets;

/**
 * @author wangbaohai
 * @ClassName LoginSuccessHandler
 * @description: 登录成功处理类
 * @date 2024年11月20日
 * @version: 1.0.0
 */
@RequiredArgsConstructor
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    private final String loginPageUri;

    private final AuthenticationSuccessHandler authenticationSuccessHandler =
            new SavedRequestAwareAuthenticationSuccessHandler();

    /**
     * 当用户成功认证后调用此方法处理成功逻辑
     *
     * @param request 用于获取请求信息，如请求头、请求参数等
     * @param response 用于向客户端发送响应信息，如重定向、返回JSON数据等
     * @param authentication 包含认证信息的对象，如用户角色、权限等
     */
    @Override
    @SneakyThrows
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) {
        // 如果是绝对路径(前后端分离)
        if (UrlUtils.isAbsoluteUrl(this.loginPageUri)) {
            // 创建一个成功结果对象，包含成功状态和消息
            Result<String> success = Result.success();
            // 设置响应字符编码，确保中文字符不会乱码
            response.setCharacterEncoding(StandardCharsets.UTF_8.name());
            // 设置响应内容类型为JSON，用于前后端交互
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            // 将成功结果对象转换为JSON字符串并写入响应体中
            response.getWriter().write(JsonUtils.objectCovertToJson(success));
            // 刷新输出流，确保数据及时发送给客户端
            response.getWriter().flush();
        } else {
            // 如果不是绝对路径，则调用自定义的成功处理器处理认证成功逻辑
            authenticationSuccessHandler.onAuthenticationSuccess(request, response, authentication);
        }
    }

}
